# 这个文件用来扫描易测项目js代码
# 获取代码中的ID，并且生成.json文件
import json
import os
import re


def scan_files(directory, prefix=None, postfix=None):
    files_list = []

    for root, sub_dirs, files in os.walk(directory):
        for special_file in files:
            if postfix:
                if special_file.endswith(postfix):
                    files_list.append(os.path.join(root, special_file).replace('\\', '/'))
            elif prefix:
                if special_file.startswith(prefix):
                    files_list.append(os.path.join(root, special_file).replace('\\', '/'))
            else:
                files_list.append(os.path.join(root, special_file).replace('\\', '/'))

    return files_list


def readFile(file):
    f = open(file, 'r', encoding='utf8')
    basename = os.path.basename(file)

    content = f.read()
    id_re = re.compile(r'testID=[\'|\"](.*)[\'|\"]')
    label_re = re.compile(r'accessibilityLabel=[\'|\"](.*)[\'|\"]')
    ids = id_re.findall(content)
    labels = label_re.findall(content)

    if len(ids):
        data = dict(zip(labels, ids))
        # 写入文件
        f2 = open(basename.replace('.tsx', '.json'), 'w', encoding='utf8')
        f2.write(json.dumps(data))
        print(f'文件写入完毕： {basename}')
    else:
        pass
        # print('not found any ids any labels!')


base = 'D:\project\easyt'

if __name__ == '__main__':
    files = scan_files(base + '\src\screens', postfix='.tsx')
    files2 = scan_files(base + '\src\components', postfix='.tsx')
    [readFile(file) for file in files]
    [readFile(file) for file in files2]
